<template>
  <div>
    <base-header class="pb-6 pb-8 pt-5 pt-md-8 bg-gradient-success">
      <b-row> </b-row>
    </base-header>

    <b-container fluid class="mt--7"> </b-container>

    <b-container fluid class="mt--6">
      <b-row class="justify-content-center">
        <b-col lg="12">
          <card header-classes="bg-transparent">
            <h3 slot="header" class="mb-0">连接实盘</h3>
            <b-row class="icon-examples">
              <b-col lg="4" md="4">
                <b-button
                  type="button"
                  title=""
                  variant="danger"
                  @click.prevent="connect_ctp(true)"
                  id="id_connect_tradableTrue"
                >
                  <div>
                    <span>今天是交易日</span>
                  </div>
                </b-button>
              </b-col>
              <b-col lg="4" md="4">
                <b-button
                  type="button"
                  title=""
                  variant="danger"
                  @click.prevent="connect_ctp(false)"
                  id="id_connect_tradableFalse"
                >
                  <div>
                    <span>今天不是交易日</span>
                  </div>
                </b-button>
              </b-col>
            </b-row>
            <hr />
            <b-row class="icon-examples">
              <b-col lg="4" md="4">
                <b-button
                  type="button"
                  title=""
                  @click.prevent="modify_strategy_hyperparams"
                  class="btn btn-info"
                  id="id_modify_strategy_hyperHps"
                >
                  <div>
                    <span>开始模拟交易</span>
                  </div>
                </b-button>
              </b-col>
              <b-col lg="4" md="4">
                <b-button
                  type="button"
                  title=""
                  @click.prevent="stop_simTrade"
                  class="btn btn-info"
                  id="id_stop_simTrade"
                >
                  <div>
                    <span>停止模拟交易</span>
                  </div>
                </b-button>
              </b-col>
            </b-row>
            <hr />

            <b-row class="icon-examples">
              <b-col lg="4" md="4">
                <b-button
                  type="button"
                  title=""
                  @click.prevent="reload_strategy_class"
                  class="btn btn-info"
                >
                  <div>
                    <span>刷新策略</span>
                  </div>
                </b-button>
              </b-col>
              <b-col lg="4" md="4">
                <b-button
                  type="button"
                  title=""
                  class="btn btn-info"
                  @click.prevent="clear_logs"
                >
                  <div>
                    <span>清除日志</span>
                  </div>
                </b-button>
              </b-col>
            </b-row>
          </card>
        </b-col>
      </b-row>

      <b-row>
        <b-col xl="4" lg="4" class="order-xl-2">
          <b-row>
            <b-col>
              <log-card>
                <template slot="log">
                  <!-- <p v-for="line in log_content" :key="line">{{ line }}</p> -->
                  <p v-for="line in logStream" :key="line">{{ line }}</p>
                </template>
              </log-card>
            </b-col>
          </b-row>
        </b-col>

        <b-col xl="8" lg="8" class="order-xl-1">
          <b-row>
            <b-col>
              <hyper-params-form>
                <template slot="vt_symbols">
                  <base-input
                    type="text"
                    label="合约代码(用,分隔)"
                    placeholder="symbol.DCE"
                    v-model="setting.vt_symbols"
                  >
                  </base-input>
                </template>
                <template slot="class_name">
                  <label :class="labelClasses"> 交易策略 </label>
                  <b-form-select
                    v-model="setting.class_name"
                    :options="options.class_names"
                  ></b-form-select>
                </template>
              </hyper-params-form>
            </b-col>
          </b-row>
          <b-row>
            <b-col class="order-xl-1">
              <accounts-table ref="accounts_table"></accounts-table>
            </b-col>
          </b-row>
          <b-row>
            <b-col class="order-xl-1">
              <contracts-table ref="contracts_table"></contracts-table>
            </b-col>
          </b-row>
          <b-row>
            <b-col class="order-xl-1">
              <trade-record-table ref="trades_table" />
            </b-col>
          </b-row>
          <b-row>
            <b-col class="order-xl-1">
              <positions-table ref="positions_table"></positions-table>
            </b-col>
          </b-row>
        </b-col>
      </b-row>
      <b-modal ref="modal_strategyHps" title="设置策略超参数" hide-footer>
        <!-- style="white-space: pre-wrap;"可以显示\n为换行 -->
        <div style="white-space: pre-wrap">
          <p>策略描述：{{ strategy_docstring }}</p>
        </div>
        <!-- 注意{}被视作了空对象，判断空的js对象需要用JSON.stringify()=='{}' -->
        <div v-if="JSON.stringify(strategy_hyperparams) == '{}'">
          <p>本策略无超参数</p>
        </div>
        <b-form @submit="start_simTrade">
          <b-form-group
            v-for="(value_hps, name) in strategy_hyperparams"
            :key="name"
            :label="name"
            :label-for="'form-' + name"
          >
            <b-form-input
              :id="'form-' + name"
              type="text"
              v-model="strategy_hyperparams[name]"
            >
            </b-form-input>
          </b-form-group>
          <b-button-group>
            <b-button type="submit" variant="primary">开始模拟交易</b-button>
          </b-button-group>
        </b-form>
      </b-modal>
    </b-container>
  </div>
</template>
<script>
import HyperParamsForm from "./simTradeComponents/simTradeHyperParamsForm.vue";
import LogCard from "./simTradeComponents/LogCard.vue";
import axios from "axios";
import ContractsTable from "./simTradeComponents/ContractsTable.vue";
import AccountsTable from "./simTradeComponents/AccountsTable.vue";
import PositionsTable from "./simTradeComponents/PositionsTable.vue";
import TradeRecordTable from "../Tables/TradeRecordTable.vue";
import port_path from "../setting_RT";

const port_path_simtrade = port_path + "/simtrade";

var setting_showed;

export default {
  components: {
    HyperParamsForm,
    LogCard,
    ContractsTable,
    AccountsTable,
    PositionsTable,
    TradeRecordTable,
  },
  props: {
    labelClasses: {
      type: String,
      description: "Input label css classes",
      default: "form-control-label",
    },
  },
  data() {
    return {
      // setting是要显示给用户的回测设置
      setting: {
        vt_symbols: "symbol.DCE",
        class_name: "",
      },
      log_content: [],
      options: {
        class_names: [],
      },
      modalShow_strategyHps: false,
      strategy_hyperparams: {},
      strategy_docstring: "",
      logStream: [],
    };
  },

  methods: {
    connect_ctp(today_tradable) {
      const path =
        port_path_simtrade + "/connect_ctp/" + String(today_tradable);
      axios
        .get(path)
        .then((res) => {
          if (res.data != "False") {
            this.disable_button_by_id("id_connect_tradableTrue");
            this.disable_button_by_id("id_connect_tradableFalse");
            this.activate_button_by_id("id_modify_strategy_hyperHps");
            this.show_contracts_info(res.data["contracts"]);
            this.show_accounts_info(res.data["accounts"]);
          } else {
            this.$notify({
              type: "warning",
              message: "连接CTP失败!",
            });
          }
        })
        .catch((error) => {
          this.handle_error(error);
        });

      this.$notify({
        type: "info",
        message: "正在连接CTP...",
      });
    },

    show_class_names(class_names) {
      //在“交易策略”中显示class_names
      //对Array直接用for in遍历的是索引
      //Array.forEach(func)遍历的是对象
      this.options.class_names = [];
      class_names.forEach((class_name) => {
        this.options.class_names.push({
          value: class_name,
          text: class_name,
        });
      });
    },
    reload_strategy_class() {
      const path = port_path_simtrade + "/reload_strategy_class";
      axios
        .get(path)
        .then((res) => {
          let class_names = res.data;
          this.show_class_names(class_names);
          this.$notify({
            type: "info",
            message: "策略已刷新",
          });
        })
        .catch((error) => {
          this.handle_error(error);
        });
    },
    activate_button_by_id(id) {
      let button = document.getElementById(id);
      button.disabled = false;
      button.active = true;
    },
    disable_button_by_id(id) {
      let button = document.getElementById(id);
      button.disabled = true;
    },
    modify_strategy_hyperparams() {
      let prop;
      setting_showed = {};
      for (prop in this.setting) {
        setting_showed[prop] = this.setting[prop];
      }
      this.strategy_hyperparams = {};

      const path = port_path_simtrade + "/modify_strategy_hyperparams";
      axios
        .post(path, setting_showed)
        .then((res) => {
          if (res.data != "False") {
            let name;
            for (name in res.data) {
              if (name == "docstring") {
                this.strategy_docstring = res.data[name];
              } else {
                this.strategy_hyperparams[name] = res.data[name];
              }
            }
            this.$refs["modal_strategyHps"].show();
          } else {
          }
        })
        .catch((error) => {
          this.handle_error(error);
        });
    },
    start_simTrade(evt) {
      evt.preventDefault();

      const path = port_path_simtrade + "/start_simTrade";
      axios
        .post(path, this.strategy_hyperparams)
        .then((res) => {
          if (res.data != "False") {
            this.activate_button_by_id("id_stop_simTrade");
            this.$notify({
              type: "info",
              message: "模拟交易启动成功！",
            });
          } else {
            this.$notify({
              type: "warning",
              message: "模拟交易启动失败！",
            });
          }
        })
        .catch((error) => {
          this.handle_error(error);
        });

      this.$refs["modal_strategyHps"].hide();
      this.$notify({
        type: "info",
        message: "启动模拟交易中...",
      });
    },
    stop_simTrade() {
      const path = port_path_simtrade + "/stop_simTrade";
      axios
        .post(path)
        .then((res) => {
          if (res.data != "False") {
            this.show_accounts_info(res.data["accounts"]);
            this.show_positions_info(res.data["positions"]);
            this.show_trades_info(res.data["trades"]);
            this.$notify({
              type: "info",
              message: "停止模拟交易成功！",
            });
            this.activate_button_by_id("id_modify_strategy_hyperHps");
            this.disable_button_by_id("id_stop_simTrade");
          } else {
            this.$notify({
              type: "warning",
              message: "停止模拟交易失败！",
            });
          }
        })
        .catch((error) => {
          this.handle_error(error);
        });
    },
    clear_logs() {
      const path = port_path_simtrade + "/log";
      axios
        .delete(path)
        .then((res) => {})
        .catch((error) => {
          this.handle_error(error);
        });
    },
    handle_error(error) {
      this.$notify({
        type: "warning",
        message: error,
      });
    },
    show_contracts_info(data) {
      this.$refs.contracts_table.update_tableData(data);
    },
    show_accounts_info(data) {
      this.$refs.accounts_table.update_tableData(data);
    },
    show_positions_info(data) {
      this.$refs.positions_table.update_tableData(data);
    },
    show_trades_info(data) {
      this.$refs.trades_table.update_tableData(data);
    },
    load_class_names() {
      const path = port_path_simtrade + "/class_names";
      axios
        .get(path)
        .then((res) => {
          let class_names = res.data;
          this.show_class_names(class_names);
        })
        .catch((error) => {
          this.handle_error(error);
        });
    },
    startStreaming() {
      const stream = new EventSource(port_path_simtrade + "/stream_log");
      stream.onmessage = (event) => {
        this.logStream = JSON.parse(event.data);
      };
    },
  },
  created() {
    this.load_class_names();
    // window.myData = this;
  },
  mounted() {
    this.disable_button_by_id("id_modify_strategy_hyperHps");
    this.disable_button_by_id("id_stop_simTrade");
    //监听stream通信
    this.startStreaming();
  },
};
</script>
<style>
</style>
